RED_TEAM  = 1
BLUE_TEAM = 2

/*---------------------------------------------------------
   Name: gamemode:PlayerSelectSpawn( player )
   Desc: Find a spawn point entity for this player
---------------------------------------------------------*/
function GM:PlayerSelectSpawn( pl )

	if ( !self.Spawns ) then
		self.Spawns = {}
		self.Spawns[ RED_TEAM  ] = ents.FindByClass( "red_team" )
		self.Spawns[ RED_TEAM  ] = table.Add( self.Spawns[ RED_TEAM  ], ents.FindByClass( "info_player_combine" ) )
		self.Spawns[ RED_TEAM  ] = table.Add( self.Spawns[ RED_TEAM  ], ents.FindByClass( "info_player_terrorist" ) )
		self.Spawns[ RED_TEAM  ] = table.Add( self.Spawns[ RED_TEAM  ], ents.FindByClass( "info_player_axis" ) )

		self.Spawns[ BLUE_TEAM ] = ents.FindByClass( "blue_team" )
		self.Spawns[ BLUE_TEAM ] = table.Add( self.Spawns[ BLUE_TEAM ], ents.FindByClass( "info_player_rebel" ) )
		self.Spawns[ BLUE_TEAM ] = table.Add( self.Spawns[ BLUE_TEAM ], ents.FindByClass( "info_player_counterterrorist" ) )
		self.Spawns[ BLUE_TEAM ] = table.Add( self.Spawns[ BLUE_TEAM ], ents.FindByClass( "info_player_allies" ) )

		self.Spawns["fallback"] = ents.FindByClass( "info_player_start" )
	end

	local team = pl:Team()
	local SpawnTable = self.Spawns[ team ]
	local Spawnpoint = nil

	// I didn't like how spawn points were allocated as players could sometimes get stuck inside each other, or inside props.
	// This method should be a bit more reliable
	if ( SpawnTable ) then

		//Put the spawnpoints in a random order
		local temp = {}
		for _,v in pairs( SpawnTable ) do table.insert( temp, math.random( 1, #temp+1 ), v ) end

		//Check each spawnpoint to see if we're gonna get stuck & use the first 'empty' one we come across
		for _,Spawnpoint in pairs( temp ) do
			if !( #ents.FindInSphere( Spawnpoint:GetPos(), 16 ) > 1 ) then return Spawnpoint end
		end

	end

	// In case there's no spawnpoints available use an info_player_start.
	return self.Spawns[ "fallback" ][ 1 ]

end